/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.servlets.pages;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import ru.miit.elearning.hibernate.dao.GenericDAO;
import ru.miit.elearning.hibernate.dao.HibernateUtil;

/**
 *
 * @author Cyclone
 */
public class CurriculumUserServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        Session session = null;

        int id = -1;
        boolean isMyCurriculum = false;

        try {

            String idString = request.getParameter("id");

            session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();

            GenericDAO genericDAO = new GenericDAO(session);

            int currentUserId = genericDAO.findUserIdByLogin(request.getRemoteUser());

            if (idString == null || idString.length() < 1) {
                id = currentUserId;
                isMyCurriculum = true;
            } else {
                id = Integer.parseInt(idString);
                if (id == currentUserId) {
                    isMyCurriculum = true;
                }
            }
            boolean isCurrentUserAdmin = request.isUserInRole("admin");
            boolean isCurrentUserTutor = request.isUserInRole("tutor");

            if (!isMyCurriculum && !isCurrentUserAdmin && !isCurrentUserTutor) {
                // student
                out.print("<p>Вы можете просмотреть только свой учебный журнал - <a href='Curriculum'>перейти</a></p>.");
            } else {

                // String parameters = "?id=" + id + "&isMyCurriculum=" + isMyCurriculum;

                boolean isUserInRoleTutor = genericDAO.isUserInRoleTutor(id);
                boolean isUserInRoleStudent = genericDAO.isUserInRoleStudent(id);

                if (!isUserInRoleStudent && !isUserInRoleTutor) {
                    out.print("<p>Выбранный пользователь не является студентом или тьютором и не имеет учебного журнала.");
                    if (request.isUserInRole("admin")) {
                        out.println("<br/>"
                                + "<a href=Profile?id=" + id + ">Профиль пользователя</a>");
                    }
                    out.print("</p>");
                } else {

                    if ((isCurrentUserAdmin || isMyCurriculum) && isUserInRoleTutor && isUserInRoleStudent) {

                        out.println("<form id=\"form\" class=\"rounded-formcascade\"><fieldset><legend>Выбор профиля учебного журнала</legend>");
                        out.println("<a href=\"CurriculumTutor?id=" + id + "\"><input type=\"button\" id=\"button1\" value=\"Журнал тьютора\" /></a>");
                        out.println("<a href=\"CurriculumStudent?id" + id + "\"><input type=\"button\" id=\"button2\" value=\"Журнал студента\" /></a>");
                        out.println("</fieldset></form>");

                        out.println("<script type='text/javascript'>");
                        out.println("$(document).ready(function() {");
                        if (isMyCurriculum) {
                            out.println("$(\"#liCurriculum\").addClass(\"current\");");
                        } else {
                            out.println("$(\"#liUsers\").addClass(\"current\");");
                        }
                        out.println("});");
                        out.println("</script>");

                    } else {
                        if (isUserInRoleStudent) {
                            getServletContext().getRequestDispatcher("/CurriculumStudent?id=" + id).forward(request, response);
                        } else {
                            if (isUserInRoleTutor) {
                                getServletContext().getRequestDispatcher("/CurriculumTutor?id=" + id).forward(request, response);
                                
                            }
                        }
                    }
                }
            }
            if (session != null && session.isConnected()) {
                session.getTransaction().commit();
            }

        } catch (Exception e) {
            Logger.getLogger(CurriculumUserServlet.class.getName()).log(Level.SEVERE, null, e);
            if (session != null && session.isConnected()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        } finally {
            if (session != null && session.isConnected()) {
                session.close();
            }
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
